package org.richin.net.util;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * <b>标题:</b> 网络测试工具包.
 * <pre><b>描述:</b>
 *   网络测试工具包，需要JDK5以上支持
 * </pre>
 *
 * @author <a href="mailto:littcai@hotmail.com">空心大白菜</a>
 * @since Nov 7, 2007
 * @version 1.0
 *
 */
public class NetUtil
{
        private transient static final Log logger = LogFactory.getLog(NetUtil.class);

    /**
     * 模拟PING操作，测试网络连通性。连接成功返回true，否则返回false
     * @param ip
     * @return
     */
    public static boolean ping(String ip)
    {
        boolean ret = false;
        try {
            InetAddress address = InetAddress.getByName(ip);
            ret = address.isReachable(5000);
            if(logger.isDebugEnabled())
            {
                logger.debug("PING网元设备，IP地址："+ ip +"，结果："+ret);
            }
        } catch (UnknownHostException e) {
            ret = false;
        } catch (IOException e) {
            ret = false;
        }
        return ret;
    }

    /**
     * 模拟TELNET操作，连接成功返回true，否则返回false
     * @return
     */
    public static boolean telnet(String ip,int port)
    {
        boolean ret = false;
        Socket server = null;
        try {
            server = new Socket();
            InetSocketAddress address = new InetSocketAddress(ip,port);
            server.connect(address, 5000);
            ret = true;
        } catch (UnknownHostException e) {
            ret = false;
        } catch (IOException e) {
            ret = false;
        }finally{
            if(server!=null)
                try{
                    server.close();
                } catch (IOException e) {
                }
        }
        return ret;
    }
    /**
     * 通过给定的网址生成InputStream
     * @param uri
     * @return
     * @throws IOException
     * @throws MalformedURLException
     */
	public static InputStream getIs(String uri) throws IOException, MalformedURLException {
		HttpURLConnection connection = (HttpURLConnection) new URL(uri).openConnection();
		connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon;)");
		InputStream is = connection.getInputStream();
		return is;
	}
    /**
     * @param args
     */
    public static void main(String[] args)
    {
        System.out.println(NetUtil.ping("http://sports.yinsha.com/file/200610/2006102408511470/8.jpg"));
        System.out.println(NetUtil.ping("http://bbs.evocn.com/uploadpic/7/200604/2006042416552218941.jpg"));
       // System.out.println(NetUtil.telnet("127.0.0.1",23));
        //System.out.println();
    }


}
